/**
 * 登录页面加载检测和修复工具
 */

// 检测登录页面是否正常加载
export function detectLoginPageLoading() {
  return new Promise((resolve) => {
    const checkInterval = setInterval(() => {
      const loginContainer = document.querySelector('.login-container')
      const loginCard = document.querySelector('.login-card')
      const loginForm = document.querySelector('.login-form')
      
      if (loginContainer && loginCard && loginForm) {
        clearInterval(checkInterval)
        resolve(true)
      }
    }, 100)
    
    // 5秒后超时
    setTimeout(() => {
      clearInterval(checkInterval)
      resolve(false)
    }, 5000)
  })
}

// 强制重新渲染登录页面
export function forceRenderLoginPage() {
  const app = document.getElementById('app')
  if (app) {
    // 清空内容
    app.innerHTML = ''
    
    // 添加加载提示
    const loadingDiv = document.createElement('div')
    loadingDiv.style.cssText = `
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      font-family: 'Microsoft YaHei', sans-serif;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    `
    loadingDiv.innerHTML = `
      <div style="text-align: center; color: white;">
        <div style="margin-bottom: 20px;">
          <div style="
            width: 40px;
            height: 40px;
            border: 4px solid rgba(255,255,255,0.3);
            border-top: 4px solid white;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto;
          "></div>
        </div>
        <div>正在加载登录页面...</div>
        <div style="font-size: 12px; margin-top: 10px; opacity: 0.8;">如果长时间无响应，请刷新页面</div>
      </div>
      <style>
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
      </style>
    `
    app.appendChild(loadingDiv)
    
    // 3秒后尝试刷新页面
    setTimeout(() => {
      if (!document.querySelector('.login-container')) {
        if (confirm('登录页面加载失败，是否刷新页面？')) {
          window.location.reload()
        }
      }
    }, 3000)
  }
}

// 监控登录页面状态
export function monitorLoginPage() {
  // 只在登录页面执行
  if (window.location.pathname.includes('/login') || window.location.hash.includes('/login')) {
    detectLoginPageLoading().then(loaded => {
      if (!loaded) {
        console.warn('登录页面加载失败，尝试强制重新渲染')
        forceRenderLoginPage()
      } else {
        console.log('登录页面加载成功')
      }
    })
  }
}

// 添加页面可见性检测
export function setupVisibilityDetection() {
  document.addEventListener('visibilitychange', () => {
    if (!document.hidden) {
      // 页面重新可见时检查登录页面
      setTimeout(() => {
        monitorLoginPage()
      }, 500)
    }
  })
}

// 添加网络状态检测
export function setupNetworkDetection() {
  window.addEventListener('online', () => {
    console.log('网络连接恢复')
    // 网络恢复时重新检查页面
    setTimeout(() => {
      monitorLoginPage()
    }, 1000)
  })
  
  window.addEventListener('offline', () => {
    console.warn('网络连接断开')
    // 显示离线提示
    const offlineDiv = document.createElement('div')
    offlineDiv.id = 'offline-notice'
    offlineDiv.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      background: #dc3545;
      color: white;
      padding: 10px;
      text-align: center;
      z-index: 10000;
      font-size: 14px;
    `
    offlineDiv.textContent = '网络连接已断开，请检查网络设置'
    document.body.appendChild(offlineDiv)
  })
}

// 初始化所有检测功能
export function initLoginPageDetection() {
  // 页面加载完成后开始监控
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
      setTimeout(() => {
        monitorLoginPage()
        setupVisibilityDetection()
        setupNetworkDetection()
      }, 1000)
    })
  } else {
    setTimeout(() => {
      monitorLoginPage()
      setupVisibilityDetection()
      setupNetworkDetection()
    }, 1000)
  }
}